package com.xiyuan.smartutils.template.engine;

import com.xiyuan.smartutils.Files;
import com.xiyuan.smartutils.Resources;
import com.xiyuan.smartutils.crypto.MD5;

import java.io.File;

import static com.xiyuan.smartutils.template.engine.Templates.cache;
import static com.xiyuan.smartutils.template.engine.Templates.getTemplate;

/**
 * 模板解析器
 *
 * @author xiyuan-lgz 2025-02-22 @version v1.0.0 新建与整理
 */
public class TemplateResolver {
    
    static Template resolveText(String id, String viewPath, String content) {
        Template view = StatementParser.parseContent(viewPath, content);
        view.setLastModified(System.currentTimeMillis());
        return view.setId(id);
    }
    
    public static Template resolveFile(String filePath) {
        try {
            Template view = getTemplate(filePath);
            File file = new File(filePath);
            String resource = null;
            long lastModified = view == null ? 0L : view.getLastModified();
            if (file.exists() && file.isFile() && file.canRead()) {
                lastModified = file.lastModified();
                if (view == null || view.getLastModified() != lastModified) {
                    resource = Files.readUTF8(file);
                    view = null;
                }
            }
            else if (view == null && Resources.exists(filePath)) {
                lastModified = System.currentTimeMillis();
                resource = Resources.getResourceStringUTF8(filePath);
            }
            if (view != null) {return view;}
            
            if (resource != null) {
                view = resolveText(MD5.encodeUTF8(resource), filePath, resource);
                view.setLastModified(lastModified);
                Throwable error = view.getError();
                if (error != null) throw error;
                // 保存新页面
                cache(filePath, view);
            }
            return view;
        }
        catch (RuntimeException e) {
            throw e;
        }
        catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
